<template>
  <div>
    <el-table :data="items" border>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="info" label="商品信息"></el-table-column>
      <el-table-column prop="price" label="商品价格"></el-table-column>
      <el-table-column label="商品数量" width="180">
        <template slot-scope="scope">
          <el-input
              v-model="scope.row.quantity"
              type="number"
              placeholder="商品数量"
              @change="calculateTotalPrice"
          ></el-input>
        </template>
      </el-table-column>
    </el-table>
    <div class="total-price">
      合计：{{ totalPrice }}
    </div>
    <el-button
        type="primary"
        @click="submit"
    >
      结算
    </el-button>
  </div>
</template>


<script>
import {getSessionStorage} from "@/common";
import axios from "axios";
import qs from "qs";
import router from "@/router";

export default {
  name: "ShopInfo",
  data() {
    return {
      shopId: this.$route.query.shopId,
      items: [],
      user: {},
      totalPrice: 0,
      quantityMap: {}
    }
  },
  created() {
    this.user = getSessionStorage('user')
    axios.post("/item/query", qs.stringify({
      shopId: this.shopId
    })).then(response => {
      this.items = response.data.data
      console.log(this.items)
    })
  },
  methods: {
    calculateTotalPrice() {
      let total = 0
      for (const item of this.items) {
        total += item.price * item.quantity
        this.quantityMap[item.itemId] = item.quantity
      }
      this.totalPrice = total
    },
    submit() {
      let result = [];
      for (let item of this.items) {
        result.push({
          id: item.itemId,
          quantity: this.quantityMap[item.itemId]
        });
      }
      let to = {
        shopId: this.shopId,
        userId: this.user.userId,
        itemList: result,
        totalPrice: this.totalPrice
      }
      console.log(to)
      // 向后台发送集合数据，创建订单
      axios.post('/order/createOrder', to).then(response => {
        if (response.data === -1){
          alert('商品添加成功!')
        }
        console.log(response);
        router.push({
          path:'/orderList',
        })
      });
    }
  }
}
</script>

<style>
.total-price {
  font-size: 18px;
  color: red;
}
</style>